package com.ojoin.trade.supplyloan_core.web.service.impl;

import java.io.Serializable;

import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.Session;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.stereotype.Service;

import com.ojoin.trade.common.utils.Config;
import com.ojoin.trade.common.utils.LogUtils;
import com.ojoin.trade.common.utils.json.JSONUtils;
import com.ojoin.trade.supplyloan_core.web.service.QueueSenderServie;

@Service
public class QueueSenderServieImpl implements QueueSenderServie {
	// QueueReceiverCatachListener
	public static final String CATCHDATA = "catchData";

	private static final Logger log =LoggerFactory.getLogger(QueueSenderServieImpl.class);
	@Autowired
	@Qualifier("jmsQueueTemplate")
	private JmsTemplate jmsTemplate;// 通过@Qualifier修饰符来注入对应的bean

	public JmsTemplate getJmsTemplate() {
		return jmsTemplate;
	}

	public void setJmsTemplate(JmsTemplate jmsTemplate) {
		this.jmsTemplate = jmsTemplate;
	}

	@Override
	public void send(String queueName, final String message) {

		jmsTemplate.send(queueName, new MessageCreator() {
			@Override
			public Message createMessage(Session session) throws JMSException {
				return session.createTextMessage(message);
			}
		});
	}

	@Override
	public void send(Destination destination, final String message) {

		jmsTemplate.send(destination, new MessageCreator() {
			@Override
			public Message createMessage(Session session) throws JMSException {
				return session.createTextMessage(message);
			}
		});
	}

	@Override
	public void send(String queueName, final Serializable message) {
		jmsTemplate.send(queueName, new MessageCreator() {
			@Override
			public Message createMessage(Session session) throws JMSException {
				return session.createObjectMessage(message);
			}
		});

	}

	@Override
	public Message receive(final String queueName) {
		Message m = jmsTemplate.receive(queueName);
		return m;

	}

	@Override
	public boolean send(final Destination destination, final Serializable message) {
		boolean ret=true;
		try {
			jmsTemplate.send(destination, new MessageCreator() {
				@Override
				public Message createMessage(Session session) throws JMSException {
					return session.createObjectMessage(message);
				}
			});
		} catch (Exception e) {
			ret=false;
			LogUtils.error(log, e, "消息发送失败,%s", JSONUtils.toJSONString(message));
		}
		return ret;
	}

}
